from flask import Blueprint, request, jsonify
from sqlalchemy import func
from datetime import datetime, timedelta
from database import db
from models import Device, DeviceData, ProductionBatch

dashboard_bp = Blueprint('dashboard', __name__)

@dashboard_bp.route('/summary', methods=['GET'])
def get_dashboard_summary():
    """
    Get a summary of the current production status for the dashboard.
    Includes:
    - Total number of devices
    - Number of online/offline/error devices
    - Total production for today
    - Current production speed (average of all devices)
    """
    # Count devices by status
    device_counts = db.session.query(
        Device.status, func.count(Device.id)
    ).group_by(Device.status).all()

    status_counts = {
        'total': Device.query.count(),
        'online': 0,
        'offline': 0,
        'error': 0
    }

    for status, count in device_counts:
        if status in status_counts:
            status_counts[status] = count

    # Get today's production data
    today = datetime.utcnow().date()
    today_start = datetime.combine(today, datetime.min.time())

    # 使用shift_length代替production_length
    today_production = db.session.query(
        func.sum(DeviceData.shift_length)
    ).filter(DeviceData.timestamp >= today_start).scalar() or 0

    # 使用average_speed代替production_speed
    current_speed = db.session.query(
        func.avg(DeviceData.average_speed)
    ).filter(
        DeviceData.timestamp >= datetime.utcnow() - timedelta(minutes=5),
        Device.status == 'online'
    ).join(Device, DeviceData.device_id == Device.device_id).scalar() or 0

    return jsonify({
        'device_status': status_counts,
        'today_production': float(today_production),
        'current_speed': float(current_speed),
        'timestamp': datetime.utcnow().isoformat()
    }), 200

@dashboard_bp.route('/production-history', methods=['GET'])
def get_production_history():
    """
    Get historical production data for charting.
    Can filter by time period (day, week, month).
    """
    period = request.args.get('period', 'day')

    if period == 'day':
        start_time = datetime.utcnow() - timedelta(days=1)
        interval = 'hour'
    elif period == 'week':
        start_time = datetime.utcnow() - timedelta(days=7)
        interval = 'day'
    elif period == 'month':
        start_time = datetime.utcnow() - timedelta(days=30)
        interval = 'day'
    else:
        return jsonify({'error': 'Invalid period. Use day, week, or month'}), 400

    # This is a simplified query - in a real application, you would use
    # more sophisticated time-based grouping based on your database
    data_points = DeviceData.query.filter(
        DeviceData.timestamp >= start_time
    ).order_by(DeviceData.timestamp).all()

    # Process data for charting
    result = []
    for point in data_points:
        result.append({
            'timestamp': point.timestamp.isoformat(),
            'production_length': point.shift_length if hasattr(point, 'shift_length') else 0,
            'production_speed': point.average_speed if hasattr(point, 'average_speed') else 0
        })

    return jsonify({
        'period': period,
        'data': result
    }), 200

@dashboard_bp.route('/device-status', methods=['GET'])
def get_device_status():
    """
    Get the current status of all devices for the dashboard.
    """
    devices = Device.query.all()

    result = []
    for device in devices:
        # Get the latest data point for each device
        latest_data = DeviceData.query.filter_by(
            device_id=device.device_id
        ).order_by(DeviceData.timestamp.desc()).first()

        device_info = device.to_dict()
        if latest_data:
            device_info.update({
                'latest_data': latest_data.to_dict()
            })

        result.append(device_info)

    return jsonify({
        'devices': result
    }), 200

@dashboard_bp.route('/batches', methods=['GET'])
def get_production_batches():
    """
    Get information about production batches.
    """
    status = request.args.get('status')

    query = ProductionBatch.query

    if status:
        query = query.filter_by(status=status)

    batches = query.order_by(ProductionBatch.start_time.desc()).all()

    return jsonify({
        'batches': [batch.to_dict() for batch in batches]
    }), 200
